/***
 * 路由工具集
 */
import controRoute from '../kernel/route/controRoute';
import sugar from '../kernel/tools/sugar';
import config from '../init/controConfig';
import fs from 'fs'
import { ctx } from './inter';

let route_tool ={
    /***
     * 判断url是否为路由参数的路由
     * 如果有路由参数则自动生成识别这个路由的正则表达式
     * 并把正则返回
     */
    isRouter(ctx:ctx,data:routeInterface) :routeInterface{
        //解析出来注释
        let url:string = ctx.request.url.replace(/\//g,"<_GEM_>");
        
        // 遍历动态路由
        let router:routeTypeStructure = {...controRoute.getDynamicRoute(ctx.request.method), ...controRoute.getDynamicRoute("any")} as routeTypeStructure;
        
        // 参数
        let parameter:any = [];

        // 遍历获取结果
        Object.keys(router).some((value):boolean|void => {
            // 遍历出来的路由接口
            let inter:routeInterface = router[value];

            // 判断这个路由是不是属于这个
            if(inter.data.regular.test(url)){
                ctx.dynamicRoutingParameters = {};
                ctx.dynamicRoutingParametersArray = [];
                inter.data.replace
                    .reduce((par:string,e:string)=>par.replace(e,""),ctx.request.url)
                    .split("/").filter((res:any)=>res)
                    .forEach((e:string,index:number) => {
                        parameter.push(e);
                        ctx[inter.data.parameter[index]] = e;
                        ctx.dynamicRoutingParameters[inter.data.parameter[index]] = e;
                        ctx.dynamicRoutingParametersArray.push(e);
                    });
                //把路由参数解析出来
                data=inter;
                // 返回true结束循环
                return true;
            }
        });
        return data;
    },

    /***
     * 从路由集合中获取路由
     */
    async getRoute(ctx:ctx){
        let route:routeInterface = controRoute.getStaticRouteInter(ctx.request.method,ctx.request.url) ||
                                   controRoute.getStaticRouteInter("any",ctx.request.url);
        let requestParse = controRoute.getSpecialRoute("requestParse")
        //如果有路由就正常返回，没有路由
        if(!route){
            //判断一下是不是某个文件的地址
            let filepath = isFile(ctx);
            if(filepath){
                ctx.filepath = filepath;
                let _public = controRoute.getSpecialRoute("public");
                //读取配置的资源管理模块
                return {
                    modules:(controRoute.getPlug() as Array<any>).concat(requestParse.modules,requestParse.controller,_public.modules),
                    controller:_public.controller
                }
            }

            //判断是不是有路由参数的路由 返回空就代表没有
            route = this.isRouter(ctx)
            if(route){
                return {
                    modules:(controRoute.getPlug() as Array<any>).concat(requestParse.modules,requestParse.controller,route.modules),
                    controller:route.controller
                };
            }

            let _404 = controRoute.getSpecialRoute("404");
            return {
                modules:(controRoute.getPlug() as Array<controllerStructure>).concat(_404.modules as Array<controllerStructure>),
                controller:_404.controller
            };
        }

        //有路由直接返回模块数组
        return {
            modules:(controRoute.getPlug() as Array<any>).concat(requestParse.modules,requestParse.controller,route.modules),
            controller:route.controller
        };
    }
}


// 判断是文件吗
function isFile(ctx:ctx){
    let path = sugar.path(config.getAddress("public") + ctx.request.url);
    // 存在并且是一个文件
    if(fs.existsSync(path) && fs.statSync(path).isFile()){return path}

    if(path.endsWith("/")){
        path+="index.html";
        if(fs.existsSync(path)){return path}
        return false;
    }else{
        if(fs.existsSync(path+".html"))return path+".html";
        if(fs.existsSync(path+"/index.html")){
            // 关闭重定向，开启会导致一个无限请求的bug
            // ctx.redirect(path+"/");
            return path+"/index.html"
        };
    }

    return false;
}


if(module)module.exports = route_tool;
export default route_tool;